import 'package:easy_refresh/easy_refresh.dart';
import 'package:get/get.dart';
import 'package:sainbainu/common/apis/group_api.dart';
import 'package:sainbainu/common/models/request/pager_request.dart';
import 'package:sainbainu/common/repositories/group_repository.dart';
import 'package:sainbainu/common/routes/routes.dart';
import 'package:sainbainu/common/utils/loading.dart';

import 'index.dart';

class GroupListController extends GetxController {
  GroupListController();

  final state = GroupListState();

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
    state.groupRefreshController = EasyRefreshController(
      controlFinishRefresh: true,
      controlFinishLoad: true,
    );
    state.groupRepository = GroupRepository(GroupApi());
    state.groupPagerRequest = PagerRequest();
    getGroupList();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
    state.groupRefreshController.dispose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }

  /// 获取下组列表
  Future getGroupList({bool refresh = true}) async {
    if (refresh) {
      state.groupPagerRequest.pageNum = 1;
    }
    var res = await state.groupRepository.recommentList(
      state.groupPagerRequest,
    );
    if (refresh) {
      state.groupListResponse.rows = res.rows;
    } else {
      state.groupListResponse.rows.addAll(res.rows);
    }

    state.groupListResponse.total = res.total;
    state.hasGroupMore =
        state.groupPagerRequest.pageNum * state.groupPagerRequest.pageSize <
            res.total;
    state.groupPagerRequest.pageNum++;
    update(['groupList']);
  }

  /// 小组上拉下载
  Future onGroupRichBottom() async {
    try {
      if (state.hasGroupMore) {
        await getGroupList(refresh: false);
      }
      if (!state.hasGroupMore) {
        state.groupRefreshController.finishLoad(IndicatorResult.noMore);
      } else {
        state.groupRefreshController.finishLoad(IndicatorResult.success);
      }
    } catch (e) {
      state.groupRefreshController.finishLoad(IndicatorResult.fail);
    }
  }

  /// 加入、推出小组
  void handleJoin(int? groupId) {
    if (groupId == null) {
      return LoadingUtil.showError('无法加入');
    }
    state.groupRepository.join(groupId);
  }

  /// 小组详情页
  toGroupDetailPage(int? groupId, String? uniqueTag, String? cover) {
    if (groupId == null) return;
    Get.toNamed(
      AppRoutes.groupDetail,
      arguments: {
        'groupId': groupId,
        'uniqueTag': uniqueTag,
        'cover': cover,
      },
    );
  }
}
